package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.*;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.user.ArticleConstants;
import com.heima.common.exception.CustomException;
import com.heima.feigns.behavior.BehaviorFeign;
import com.heima.feigns.user.UserFeign;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.*;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.ArticleHomeDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.model.wemedia.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ApArticleServiceImpl
 * @Description TODO
 * @Author AWei
 * @DATE 2021/4/18 21:39
 * @Version 1.0
 */
@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Resource
    private AuthorMapper authorMapper;

    @Resource
    private ApArticleConfigMapper apArticleConfigMapper;

    @Resource
    private ApArticleContentMapper apArticleContentMapper;

    @Resource
    private ApArticleMapper apArticleMapper;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Resource
    private BehaviorFeign behaviorFeign;

    @Resource
    private UserFeign userFeign;

    @Resource
    private ApCollectionMapper apCollectionMapper;

    /**
     * @param articleDto 文章内容对象
     * @return 保存结果
     * @Description 保存app文章
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {
        //1. 校验参数
        if (ObjectUtils.isEmpty(articleDto)) {
            CustomException.custom(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 封装文章ApArticle对象
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);
        //3. 根据作者名称查询作者ID
        ApAuthor author = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getName, apArticle.getAuthorName()));
        if (ObjectUtils.isEmpty(author)) {
            CustomException.custom(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息不存在");
        }
        apArticle.setAuthorId(Long.valueOf(author.getId()));
        //4. 如果文章ID为null 添加文章
        if (apArticle.getId() == null) {
            // 普通文章
            apArticle.setComment(0);
            apArticle.setViews(0);
            apArticle.setCollection(0);
            apArticle.setLikes(0);
            // 保存
            save(apArticle);
        } else {
            //5. 如果文章ID不为null,则修改文章，并删除之前配置和文章内容
            ApArticle article = getById(articleDto.getId());
            if (article == null) {
                log.info("文章信息为空 : {}", articleDto.getId());
                throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery()
                    .eq(ApArticleConfig::getArticleId, apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
            updateById(apArticle);
        }
        //保存文章配置表信息
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfigMapper.insert(apArticleConfig);
        //保存文章内容表信息
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setContent(articleDto.getContent());
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContentMapper.insert(apArticleContent);
        //返回结果携带文章ID
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * @return 查询结果
     * @Description 加载文章列表
     */
    @Override
    public ResponseResult load(Short type, ArticleHomeDto dto) {
        //1. 校验参数：设置默认值
        if (ObjectUtils.isEmpty(dto.getSize()) || dto.getSize() < 1 || dto.getSize() > 50) {
            dto.setSize(10);
        }
        if (ObjectUtils.isEmpty(dto.getMaxBehotTime())) {
            dto.setMaxBehotTime(new Date());
        }
        if (ObjectUtils.isEmpty(dto.getMinBehotTime())) {
            dto.setMinBehotTime(new Date());
        }
        if (ObjectUtils.isEmpty(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //2. 判断查询类型：不存在设置为默认查询新文章
        if (!type.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !type.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //3. 查询文章列表
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, type);
        //4. 返回查询结果
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * @param dto app查看文章详情传递数据封装对象
     * @return 查询结果
     * @Description 加载文章详情
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //1. 校验参数：文章id不能为空
        if (ObjectUtils.isEmpty(dto.getArticleId())) {
            CustomException.custom(AppHttpCodeEnum.PARAM_REQUIRE, "缺少文章id");
        }
        //2. 根据文章id查询文章配置信息
        ApArticleConfig apArticleConfig = apArticleConfigMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, dto.getArticleId()));
        if (ObjectUtils.isEmpty(apArticleConfig)) {
            CustomException.custom(AppHttpCodeEnum.DATA_CUSTOM_ERROR, "文章配置信息不存在");
        }
        if (apArticleConfig.getIsDelete()) {
            CustomException.custom(AppHttpCodeEnum.DATA_CUSTOM_ERROR, "文章已删除");
        }
        if (apArticleConfig.getIsDown()) {
            CustomException.custom(AppHttpCodeEnum.DATA_CUSTOM_ERROR, "文章已下架");
        }
        //3 查询文章内容
        ApArticleContent articleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, dto.getArticleId()));
        if (ObjectUtils.isEmpty(articleContent)) {
            CustomException.custom(AppHttpCodeEnum.DATA_CUSTOM_ERROR, "文章内容不存在");
        }
        //4 返回封装结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("config", apArticleConfig);
        resultMap.put("content", articleContent);
        return ResponseResult.okResult(resultMap);
    }

    /**
     * @param dto
     * @return
     * @Description 加载文章详情的初始化配置信息，比如关注、喜欢、不喜欢等
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //1. 校验参数
        if (ObjectUtils.isEmpty(dto) || ObjectUtils.isEmpty(dto.getArticleId()) || ObjectUtils.isEmpty(dto.getAuthorId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        boolean iscollection = false, isfollow = false;

        //2. 判断是否关注
        ApUser user = AppThreadLocalUtils.getUser();
        ApAuthor apAuthor = authorMapper.selectById(dto.getAuthorId());
        if (!ObjectUtils.isEmpty(apAuthor)) {
            ApUserFollow apUserFollow = userFeign.findByUserIdAndFollowId(
                    user.getId(), apAuthor.getUserId());
            if (!ObjectUtils.isEmpty(apUserFollow)) {
                isfollow = true;
            }
        }

        //3. 判断是否点赞或不喜欢行为
        ApArticleRelationDto relationDto = new ApArticleRelationDto();
        relationDto.setArticleId(dto.getArticleId());
        relationDto.setEntryId(user.getId());
        relationDto.setType((short) 1);
        Map behaviorMap = behaviorFeign.findApArticleRelation(relationDto);

        //4.  判断是否收藏
        ApCollection apCollection = apCollectionMapper.selectOne(Wrappers.<ApCollection>lambdaQuery()
                .eq(ApCollection::getArticleId, dto.getArticleId())
                .eq(ApCollection::getEntryId, behaviorMap.get("entryId")));
        if (!ObjectUtils.isEmpty(apCollection)) {
            iscollection = true;
        }

        //5. 返回结果
        Map resultMap = new HashMap();
        resultMap.put("isfollow", isfollow);
        resultMap.put("iscollection", iscollection);
        resultMap.putAll(behaviorMap);

        return ResponseResult.okResult(resultMap);
    }
}
